package com.srwl.mytx.activity;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.core.content.res.ResourcesCompat;
import com.huantansheng.easyphotos.EasyPhotos;
import com.huantansheng.easyphotos.callback.SelectCallback;
import com.huantansheng.easyphotos.models.album.entity.Photo;
import com.srwl.easeui.widget.MyTitleBar;
import com.srwl.mytx.EaseConstant;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.domain.AliOssService;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.UserService;
import com.srwl.mytx.utils.GlideEngine;
import com.srwl.mytx.utils.GlideLoadUtils;
import com.srwl.mytx.utils.IMImageUtils;
import com.srwl.mytx.utils.ImageUtils;
import com.srwl.mytx.utils.PermissionsUtils;
import com.srwl.mytx.widget.ConfirmDialog;
import com.srwl.mytx.widget.FXAlertDialog;
import com.yalantis.ucrop.UCrop;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ProfileActivity extends BaseActivity implements View.OnClickListener, PermissionsUtils.IPermissionsResult {
    private static final String TAG = "ProfileActivity";
    private ImageView iv_avatar;
    private TextView tv_name;
    private TextView tv_phoneNumber;
    private TextView tv_gender;
    private TextView tv_sign;
    private TextView tv_area;
    private static final int REQUEST_CODE_UPDATE_PHONE_NUMBER = 4;
    private static final int REQUEST_CODE_UPDATE_NICK = 5;
    private static final int REQUEST_CODE_UPDATE_AREA = 9;
    private static final int UPDATE_SIGN = 6;


    private boolean hasChange = false;
    private Bitmap bitmap;
    private String path;
    private User myUser;
    private MyTitleBar titleBar;
    private ProgressDialog progressDialog;

//    private AMapLocation lastLocation = null;
//    private GaodeLocationClient locationClient;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tx_activity_myinfo);
        myUser = UserProfileManager.getInstance().getLoginUserInfo();
        if (myUser != null) {
            initView();
        }
    }

    private void initView() {
        titleBar = findViewById(R.id.title_bar);
        iv_avatar = this.findViewById(R.id.iv_avatar);
        tv_name = this.findViewById(R.id.tv_name);
        tv_phoneNumber = this.findViewById(R.id.tv_phone_number);
        tv_gender = this.findViewById(R.id.tv_gender);
        tv_sign = this.findViewById(R.id.tv_sign);
        tv_area = findViewById(R.id.tv_area);
        if (myUser.getArea() != null) {
            tv_area.setText(myUser.getArea());
        } else {
            tv_area.setText("正在获取...");
        }

        String name;
        if (myUser.getUsername() != null) {
            name = myUser.getUsername();
        } else {
            name = myUser.getNick();
        }
        String str_phoneNumber;
        if (myUser.getPhone() != null) {
            str_phoneNumber = myUser.getPhone();
        } else {
            str_phoneNumber = "未设置";
        }
        tv_phoneNumber.setText(str_phoneNumber);
        String gender = null;
        if (myUser.getGender() != null) {
            if (myUser.getGender().equals(1)) {
                gender = "女";
            } else if (myUser.getGender().equals(0)) {
                gender = "男";
            }
        } else {
            gender = "未设置";
        }

        path = Helper.getInstance().getBasePath() + File.separator;
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        path = path + getString(R.string.avatar_name);
        String avatarPath = myUser.getAvatar();
        // Glide.with(ProfileActivity.this).load(avatarPath).error(R.drawable.tx_default_avatar).into(iv_avatar);
        GlideLoadUtils.glideLoad(this, avatarPath, iv_avatar);
        tv_name.setText(name);

        tv_gender.setText(gender);
        //设置监听
        titleBar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ckeckChange();
            }
        });
        this.findViewById(R.id.re_avatar).setOnClickListener(this);
        this.findViewById(R.id.re_name).setOnClickListener(this);
        this.findViewById(R.id.rl_phone_number).setOnClickListener(this);
        this.findViewById(R.id.re_sex).setOnClickListener(this);
        this.findViewById(R.id.re_region).setOnClickListener(this);
        this.findViewById(R.id.re_sign).setOnClickListener(this);
        if (TextUtils.isEmpty(myUser.getArea())) {
            initLocation();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.re_avatar:

                String[] permissions = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
                PermissionsUtils.getInstance().checkPermissions(ProfileActivity.this, permissions, ProfileActivity.this);

                break;
            case R.id.re_name://用户名 禁止修改

                break;
            case R.id.rl_phone_number:
                Intent intent = new Intent(ProfileActivity.this, ModifyPhoneNumberActivity.class)
                        .putExtra(ModifyPhoneNumberActivity.PHONE_NUMBER, myUser.getPhone());
                startActivityForResult(intent, REQUEST_CODE_UPDATE_PHONE_NUMBER);
                break;
            case R.id.re_sex:
                showSexDialog();
                break;
            case R.id.re_region://地区根据 定位自动修改，不能手动修改

                break;
            case R.id.re_sign:
                // startActivityForResult(new Intent(ProfileActivity.this,
                // ModifyPhoneNumberActivity.class).putExtra("type", ModifyPhoneNumberActivity.TYPE_RE_SET_AREA).putExtra("default",myUser.gets), UPDATE_SIGN);
                break;


        }

    }


    private void pickAvatar() {

//        Matisse.from(this)
//                .choose(MimeType.ofImage())
//                //.theme(R.style.Matisse_Dracula)
//                .countable(true)
//                .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
//                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
//                .thumbnailScale(0.85f)
//                .imageEngine(new GlideEngine())
//                .capture(true)
//
//                .captureStrategy(new CaptureStrategy(true, "com.srbl.mytx.fileProvider"))
//                .forResult(EaseConstant.REQUEST_CODE_PICK_AVATAR);


        EasyPhotos.createAlbum(this, true, GlideEngine.getInstance())
                .setFileProviderAuthority("com.srbl.mytx.fileProvider")
                .setCount(1)
                // .start(EaseConstant.REQUEST_CODE_PICK_AVATAR);
                .start(new SelectCallback() {
                    @Override
                    public void onResult(ArrayList<Photo> photos, boolean isOriginal) {
                        Uri uri;
                        if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) { //10.0系统以下，不能直接使用uri ，否则很多手机 无法裁剪图片
                            uri = Uri.fromFile(new File(photos.get(0).path));
                        } else {
                            uri = photos.get(0).uri;
                        }

                        UCrop.Options options = new UCrop.Options();
                        options.setCircleDimmedLayer(true);
                        options.setToolbarColor(ResourcesCompat.getColor(getResources(), R.color.colorPrimary, null));
                        options.setStatusBarColor(ResourcesCompat.getColor(getResources(), R.color.colorPrimaryDark, null));
                        UCrop.of(uri, Uri.parse(path))
                                .withAspectRatio(1, 1)
                                .withMaxResultSize(480, 480)
                                .withOptions(options)
                                .start(ProfileActivity.this, EaseConstant.REQUEST_CODE_CROP);
                    }
                });

//        imageName = getNowTime() + ".png";
//        Intent intent2 = new Intent(Intent.ACTION_PICK, null);
//        intent2.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
//        intent2.setAction(Intent.ACTION_GET_CONTENT);
//
//        startActivityForResult(intent2, PHOTO_REQUEST_GALLERY);
    }

    private void showSexDialog() {
        String title = "性别";
        List<String> items = new ArrayList<String>();
        items.add("男");
        items.add("女");
        final User updataUser = new User();
        FXAlertDialog fxAlertDialog = new FXAlertDialog(ProfileActivity.this, title, items);
        fxAlertDialog.init(new FXAlertDialog.OnItemClickListner() {
            final User updateUser = new User();

            @Override
            public void onClick(int position) {

                switch (position) {

                    case 0:
                        updateUser.setGender(0);
                        break;
                    case 1:
                        updateUser.setGender(1);
                        break;
                }
                if (updateUser.getGender().equals(myUser.getGender())) {
                    return;
                }
                UpdateUserGenderInfo(updateUser);

            }
        });

    }

    private void UpdateUserGenderInfo(final User updateUser) {
        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("正在更新...");
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.show();
        //更新信息到服务端
        RetrofitManager.getInstance()
                .createRequest(UserService.class)
                .updateUserInfo(updateUser)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressDialog.dismiss();
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            showToast(iv_avatar, getString(R.string.system_busy));
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            return;
                        }
                        //控件的底层需要一个字符串类型
                        String gender = null;
                        if (updateUser != null) {
                            if (updateUser.getGender().equals(1)) {
                                gender = "女";
                            } else if (updateUser.getGender().equals(0)) {
                                gender = "男";
                            }
                        }
                        tv_gender.setText(gender);
                        UserProfileManager.getInstance().setUserGender(updateUser.getGender());
                        hasChange = true;
                        showToast(iv_avatar, getString(R.string.update_user_info_complete));
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {

                    }
                });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case EaseConstant.REQUEST_CODE_PICK_AVATAR:

                    if (data != null) {
//                        List<String> strings = Matisse.obtainPathResult(data);
//                        List<Uri> selectedPhotos = Matisse.obtainResult(data);
                        // Log.d("ProfileActivity", selectedPhotos.get(0).getPath());

                        UCrop.Options options = new UCrop.Options();
                        options.setCircleDimmedLayer(true);

                        options.setToolbarColor(ResourcesCompat.getColor(getResources(), R.color.common_top_bar_blue, null));
                        options.setStatusBarColor(ResourcesCompat.getColor(getResources(), R.color.common_black, null));
//                        Uri uri = selectedPhotos.get(0);

                        UCrop.of(Uri.parse(""), Uri.parse(path))
                                .withAspectRatio(1, 1)
                                .withMaxResultSize(480, 480)
                                .withOptions(options)
                                .start(this, EaseConstant.REQUEST_CODE_CROP);
                    }

                    break;
                case EaseConstant.REQUEST_CODE_CROP:
                    if (data != null) {
                        Uri resultUri = UCrop.getOutput(data);
                        bitmap = BitmapFactory.decodeFile(resultUri.getPath());
                        //返回的bitmap 不能直接赋值给bitmap,不起作用，原因未知，以后再考究
                        bitmap = IMImageUtils.toRoundBitmap(this.bitmap);
                        ImageUtils.save(bitmap, path, Bitmap.CompressFormat.PNG);
                        updateAvatar();

                    }
                    break;

                case REQUEST_CODE_UPDATE_PHONE_NUMBER:
                    String str_phoneNumber = data.getStringExtra("value");
                    if (str_phoneNumber != null) {
                        tv_phoneNumber.setText(str_phoneNumber);
                        hasChange = true;
                    }
                    break;
                case REQUEST_CODE_UPDATE_NICK:
                    String nick = data.getStringExtra("value");
                    if (nick != null) {
                        tv_name.setText(nick);
                        hasChange = true;
                    }
                    break;
                case REQUEST_CODE_UPDATE_AREA:
                    String area = data.getStringExtra("value");
                    if (!TextUtils.isEmpty(area)) {
                        tv_area.setText(area);
                        hasChange = true;
                    }
                case UPDATE_SIGN:
                    String sign = data.getStringExtra("value");
                    if (sign != null) {
                        tv_sign.setText(sign);

                    }
                    break;
            }
            super.onActivityResult(requestCode, resultCode, data);

        }
    }

    private void updateAvatar() {
        if (!Helper.getInstance().isNetworkConnected()) {
            showToast_v1(getString(R.string.network_anomalies));
            return;
        }

        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("正在更新...");
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.show();
        //第三个参数传入原头像名
        String oldAvatarPath = UserProfileManager.getInstance().getUserAvatar();
        String fileName;
        if (!TextUtils.isEmpty(oldAvatarPath)) {
            fileName = oldAvatarPath.substring(oldAvatarPath.lastIndexOf("/") + 1);
            if (fileName.contains("?")) {
                fileName = fileName.substring(0, fileName.indexOf("?"));
            }
        } else {
            fileName = IMImageUtils.genImageName();
        }

        //  new UpLoadImageTask(commonResultCallback).execute(new String[]{"avatar", avatarPath, fileName});

        AliOssService.getInstance().uploadUserAvatar(fileName, path, new AliOssService.OssListener() {
            @Override
            public void onProgressChange(int progress) {

            }

            @Override
            public void onSuccess(String objectKey) {
                Log.d(TAG, "onUploadComplete: 头像上传完成" + objectKey);
                //加个时间戳,加时间戳是为了让Glide 认为连接变动了，去文件服务器重新加载，Glide 使某个链接对应缓存失效的方法 貌似不起作用，才出此下策，，，
                objectKey = objectKey + "?t=" + System.currentTimeMillis();
                //组合成完整的远程地址，因为头像加载的地方很多，如果仅仅是用key,每次用的时候去组合，将非常麻烦，需要修改的地方太多了
                String fullUrl = AliOssService.USER_AVATAR_PRE_URL + objectKey;
                saveToService(fullUrl);
            }

            @Override
            public void onFailure(String errorCode, String message) {
                progressDialog.dismiss();
                showToast(iv_avatar, "头像上传失败");
                return;
            }
        });
    }

    /**
     * 上传完整地址到 服务器
     *
     * @param fullUrl
     */
    private void saveToService(String fullUrl) {
        //url 后面加个时间戳的无用参数，是为了让glide知道图片已经更新了，
        // 本来glide提供了.signature的方法来标识是否更新了图片，但是我用了没效果，

        UserProfileManager.getInstance().setUserAvatar(AliOssService.USER_AVATAR_PRE_URL + fullUrl);
        User user = new User();
        user.setAvatar(fullUrl);
        //把图片地址保存到服务端
        RetrofitManager.getInstance()
                .createRequest(UserService.class)
                .updateUserInfo(user)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressDialog.dismiss();
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            showToast(iv_avatar, getString(R.string.system_busy));
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            return;
                        }

                        Log.i(TAG, "onResponse: 更新个人信息完成");
                        UserProfileManager.getInstance().setUserAvatar(fullUrl);
                        iv_avatar.setImageBitmap(bitmap);
                        hasChange = true;
                        showToast(iv_avatar, getString(R.string.update_avatar_complete));
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        progressDialog.dismiss();
                        showToast(iv_avatar, getString(R.string.system_busy));
                        return;
                    }
                });
    }

    @Override
    public void back(View view) {
        ckeckChange();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getRepeatCount() == 0) {
            ckeckChange();

            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void ckeckChange() {

        if (hasChange) {
            setResult(RESULT_OK);
        }
        finish();
    }

    private String getImagePath(Uri uri, String seletion) {
        String path = null;
        Cursor cursor = getContentResolver().query(uri, null, seletion, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
            }
            cursor.close();

        }
        return path;
    }


    private void initLocation() {

//        locationClient = new GaodeLocationClient(this);
//        locationClient.setLocationListener(new GaodeLocationClient.LocationListener() {
//            @Override
//            public void locationSuccess(AMapLocation location) {
//                lastLocation =location;
//            }
//        });


    }

    @Override
    protected void onResume() {

        super.onResume();
    }

    @Override
    protected void onDestroy() {

        super.onDestroy();
        PermissionsUtils.getInstance().clear();
    }


    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionsUtils.getInstance().onRequestPermissionsResult(requestCode, permissions, grantResults);

    }

    @Override
    public void onGranted() {
        pickAvatar();
    }

    @Override
    public void onDenied(List<String> deniedPermissionList) {
        ConfirmDialog dialog = new ConfirmDialog(ProfileActivity.this, "提醒", "使用 [储存空间] 的权限被禁止，去设置？", "去设置", "取消", true);
        dialog.setConfirmListener(new ConfirmDialog.ConfirmListener() {
            @Override
            public void confirm() {
                Uri packageURI = Uri.parse("package:" + getPackageName());
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                startActivity(intent);
            }
        });

        dialog.show();
    }
}
